package com.itheima.domain.exhandler;

import com.itheima.domain.ex.CustomException;
import com.itheima.domain.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;



@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    //处理异常
    //@ExceptionHandler
    public Result handleException(Exception e){//方法形参中指定能够处理的异常类型
        log.error("捕获到异常:{}",e.getMessage());
        return Result.error("对不起,操作失败,请联系管理员");
    }


     //处理自定义异常


    @ExceptionHandler
    public Result handleCustomException(CustomException e){
        log.error("捕获到异常:{}",e.getMessage());
        return Result.error(e.getMessage());
    }


    @ExceptionHandler
    public Result handleCustomException(DuplicateKeyException e){
        log.error("捕获到异常:{}",e.getMessage());
        String msg = e.getMessage();
        if(msg.contains("Duplicate entry")){
            msg = msg.substring(msg.indexOf("Duplicate entry")+15,msg.indexOf("for key"))+"已存在";
        }
        return Result.error(msg);
    }

}
